package com.amadeus.commons.log.config;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class InputConfigService implements ConfigService {

	private static ConfigService inputConfigService = null;

	private InputConfigService() {
	}

	@Override
	public List<NamedNodeMap> loadConfig(String platform, String logType) {

		List<NamedNodeMap> list = new ArrayList<>();

		try {
			DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
			domFactory.setNamespaceAware(true);
			DocumentBuilder builder = domFactory.newDocumentBuilder();
			Document doc = builder.parse("input-config.xml");

			XPathFactory factory = XPathFactory.newInstance();
			XPath xpath = factory.newXPath();
			XPathExpression expr = xpath.compile("//platform[@name='" + platform + "']/log[@type='" + logType + "']/dir");

			Object result = expr.evaluate(doc, XPathConstants.NODESET);
			NodeList nodes = (NodeList) result;
			for (int i = 0; i < nodes.getLength(); i++) {
				NamedNodeMap namedNodeMap = nodes.item(i).getAttributes();
				list.add(namedNodeMap);
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}

		return list;

	}

	public static synchronized ConfigService getInstance() {
		if (null == inputConfigService) {
			inputConfigService = new InputConfigService();
		}
		return inputConfigService;
	}

	@Override
	public List<Path> paths(String platform, String logType) {
		List<Path> paths = new ArrayList<>();
		List<NamedNodeMap> listNamedNodeMaps = loadConfig(platform, logType);
		for (NamedNodeMap namedNodeMap : listNamedNodeMaps) {
			Path dir = Paths.get(namedNodeMap.getNamedItem("path").getNodeValue());
			paths.add(dir);
		}
		return paths;
	}
}
